<template>
  <div>
    <el-dialog title="在线打款" :model-value="props.modelValue" width="800px" @open="onLineOpen" @close="$emit('update:modelValue', false)" :close-on-click-modal="false">
      <el-form :model="paymentModalFormData" :rules="rules" ref="formRef" label-suffix=":">
        <el-form-item label="业务类型" prop="busType">
          <el-select style="width: 100%"  placeholder="请选择业务类型" v-model="paymentModalFormData.busType">
            <el-option v-for="item in props.businessTypeOptions"   :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目选择" prop="taskId">
          <el-select style="width: 100%"  placeholder="请选择项目"  v-model="paymentModalFormData.taskId" @change="selectTask">
            <el-option v-for="item in projectOptions" :key="item.id" :label="'【'+item.no+'】'+item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="产品选择" prop="proId">
          <el-select style="width: 100%"  placeholder="请选择产品" v-model="paymentModalFormData.id" @change="selectPro">
            <el-option v-for="item in merchantOptions" :key="item.id" :label="getProInfo(item)" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="showProDetail">
          <template #label>
            <span style="width: 4rem;"></span>
          </template>
          <div class="product-detail">
            <el-descriptions :column="1">
              <template #title>
                <div class="product-detail__title">
                  <img width="20" src="@/assets/logo/ticket.png" alt="" />
                  <span>
                    {{`产品编号:${projectDetails?.proNo || ''}`}}
                  </span>
                </div>
              </template>
              <el-descriptions-item label="服务费率:"><span style="font-weight: 700;">{{projectDetails?.serviceCharge}}%</span></el-descriptions-item>
              <el-descriptions-item label="产品限额:"><span style="font-weight: 700;">{{proxy.convertFenToYuan(projectDetails?.maxMonth) || ''}}</span></el-descriptions-item>
              <!-- 1:个人应得计费、2:开票金额计费 -->
              <el-descriptions-item label="计费模式:" :span="2"><span style="font-weight: 700;">{{
                projectDetails?.chargeMode === 1 ? '个人应得计费' :  projectDetails?.chargeMode === 2 ? '开票金额计费' : ''
              }}</span></el-descriptions-item>
              <!-- 结算方式（1：到卡 2：余额） -->
              <el-descriptions-item label="到账方式:">
                <span style="font-weight: 700;">
                  {{projectDetails?.settlementStyle === 1 ? '到卡' : projectDetails?.settlementStyle === 2 ? '余额' : ''}}
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="开票项目:">
                {{projectDetails?.invoiceItems}}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-form-item>

        <el-form-item label="服务费承担方" prop="serviceChargeType">
          <el-radio-group style="width: 100%" v-model="paymentModalFormData.serviceChargeType">
            <el-radio :label="1">用工企业承担</el-radio>
            <el-radio :label="2">自由职业者承担</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="批次号" prop="no">
          <el-input v-model="paymentModalFormData.no" placeholder="请输入批次号如:20">
            <template #prepend>{{moment().format('YYYYMMDD')}}-</template>
          </el-input>
        </el-form-item>

       <!--  <el-form-item label="人员"> </el-form-item> -->
          <editable-table ref="tableRef" :data="tableData" :columns="columnsConfig" style="width: 100%;">
            <template #operate="{ row, $index }">
              <el-icon disabled style="color: #1890ff;cursor: pointer;" v-if="$index === 0" @click="add(row)" :size="25"><CirclePlus /></el-icon>
              <el-icon v-else style="color: red;cursor: pointer;" @click="del(row)" :size="25"><CircleClose /></el-icon>
            </template>
          </editable-table>

      </el-form>
      <div style="margin-top: 5px;">
        <span style="font-size: 12px;color: #666;"> 温馨提示：最多添加10个自由职业者 </span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="$emit('update:modelValue', false)">关闭</el-button>
          <el-button type="primary" @click="onSubmit" :loading="loading"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import moment from 'moment';
import type { FormInstance, FormRules } from 'element-plus'
import EditableTable from '@/components/EditableTable/index.vue'
import useUserStore from '@/store/modules/user'

const loading = ref(false)
const projectOptions = ref([])
const merchantOptions = ref([])
const showProDetail = ref(false)
const emit = defineEmits(['update:modelValue', 'onSuccess'])
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const {invoice_type} = toRefs(proxy?.useDict("invoice_type"));



const formRef = ref<FormInstance>()
const projectDetails = ref({});
const selTask = ref({});
const paymentModalFormData = ref({
  id: '',
  no: '',
  busType: '',
  taskId: '',
  taskNo: '',
  proId: '',
  proNo: '',
  serviceChargeType: 1, // 1:用工企业承担 2:自由职业者承担
})


const isNumericString =  (str:any)=> {
  return /^\d+$/.test(str);
}

const numberValida = (rule: any, value: string, callback: any) => {
  if (!isNumericString(value)) {
    callback(new Error("格式错误,请输入数字"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules<RuleForm>>({
  no: [
    { required: true, message: "批次号不能为空", trigger: 'change' }, {
    required: true,
    validator: numberValida,
    trigger: "blur"
  }  ],
    busType: [
    {
      required: true,
      message: "业务类型不能为空",
      trigger: 'change',
    },
  ],
  serviceChargeType: [
    {
      required: true,
       message: "服务费承担方不能为空",
      trigger: 'change',
    },
  ],
  taskId: [
    {
      required: true,
      message: "项目不能为空",
      trigger: 'change',
    },
  ],
  id: [
    {
      required: true,
       message: "产品不能为空",
      trigger: 'change',
    },
  ],
})

const tableRef = ref()

const tableData = ref([
    { workerName: '', cardId: '', moneyDecimal: '', id: 1, billRemark: '' },
]);

const onLineOpen = ()=>{
    formRef.value?.resetFields();
    projectOptions.value = [];
    merchantOptions.value = [];
    showProDetail.value = false;
    tableData.value = [
        { workerName: '', cardId: '', moneyDecimal: '', id: 1, billRemark: '' },
    ];
}





watch(() => paymentModalFormData.value.busType, async (busType) => {

  if(!busType){
    return ;
  }
  paymentModalFormData.taskId = ''
  paymentModalFormData.proId = ''
  let defaultProvider = useUserStore().defaultProvider;

  const { data } = await useRequest('/payment/task/queryList', 'GET', {
    params: { busType, sydId: defaultProvider.sydId,status:1,taskStatus:7,classify:1 }
  }, { immediate: true })


  if (data) {
    projectOptions.value = data.value
  }

  const { data: merchantList } = await useRequest('/payment/merchantProduct/queryList', 'GET', {
    params: { busType, sydId: defaultProvider.sydId }
  }, { immediate: true })


  if (merchantList) {
    merchantOptions.value = merchantList.value
  }
})


const onSubmit = () => {

formRef.value?.validate(async passed => {
  if (passed) {
  tableRef.value.form.validate(valid => {
    if (valid) {
          let defaultProvider = useUserStore().defaultProvider;
          loading.value = true
          const submitData = {
            ...paymentModalFormData.value,
            no: `${moment().format('YYYYMMDD')}-${paymentModalFormData.value.no}`,
            maxMonth: projectDetails.value.maxMonth,
            proId:projectDetails.value.proId,
            chargeMode: projectDetails.value.chargeMode,
            merId: defaultProvider.merId,
            sydNo: defaultProvider.sydNo,
            invoiceType: projectDetails.value.invoiceType,
            channelCode: projectDetails.value.channelCode,
            proNo: projectDetails.value.proNo,
            merNo: defaultProvider.merNo,
            taskId: selTask.value.id,
            taskNo: selTask.value.no,
            settlementStyle: projectDetails.value.settlementStyle,
            sydId: defaultProvider.sydId,
            sydNo:defaultProvider.sydNo,
            passage:defaultProvider.bankType,
            serviceChargeRate: projectDetails.value.serviceCharge,
            details: tableData.value
          }


          console.log(submitData);


          /**
           * TODO: 接口报错
           * 为什么接口需要这么多的参数？
          */
          useRequest('/payment/bill/onlinePaymentImport', 'POST', {
            data: submitData
          }, { immediate: true,

            onSuccess: (res) => {
              const {list,errorList,analysis,allRecords} = res;
              emit('update:modelValue', false);
              emit('onSuccess', {
                code: 200,
                success: errorList.length> 0 ?false:true,
                allRecords:allRecords,
                params:submitData,
                analysis:analysis,
                msg: '操作成功',
                data: {
                  list: list,
                  errorList: errorList,
                  analysis: 'analysis',
                }
              })
            },
            onFinish: () => {
              loading.value = false
            },
           })


        }
      })

    } else {
      console.log('error');
    }
  })

}

const moneyDecimalValidation = (rule: any, value: string, callback: any) => {
  if (parseFloat(value) < 10) {
    callback(new Error("金额不能小于10"));
  } else {
    callback();
  }
};

const columnsConfig = ref([
  { label: '姓名', prop: 'workerName', type: 'input', editable: true, formItemProps: {
    rules: [{ required: true, message: '请输入姓名'  }]
  } },
  { label: '身份证号', prop: 'cardId', type: 'input', width:220, editable: true, formItemProps: {
    rules: [{ required: true, message: '请输入身份证号'  }]
  } },
  { label: '金额（元）', prop: 'moneyDecimal', type: 'number',min:10,width:120, editable: true,fieldProps:{
    type:'number',min:10
  }, formItemProps: {
    rules: [{ required: true, message: '请输入金额'  }, {
    required: true,
    validator: moneyDecimalValidation,
    trigger: "blur"
  }]
  } },
  { label: '转账附言', prop: 'billRemark', type: 'input',width:220,  editable: true, formItemProps: {
    rules: []
  } },
]);

const add = (data) => {
  if (tableData.value.length > 9) {
    ElMessage.warning('最多添加10个自由职业者')
    return
  }
  tableData.value = [...tableData.value, {workerName: '', gender: '', id: +new Date()}]
}

const del = (data) => {
  tableData.value = tableData.value.filter((item) => item.id !== data.id)
}

const getInvoiceType = (val)=>{
  return proxy?.getDicValue(val,invoice_type.value);
}

const getProInfo = (item:any)=>{
    let chargeMode = item?.chargeMode === 1 ? '个人应得计费' :  item?.chargeMode === 2 ? '开票金额计费' : ''
    return item.proNo +"-"+getInvoiceType(item.invoiceType)+"-"+chargeMode+"-"+ item.serviceCharge+"%";
}


const selectPro = (val:any)=>{

    let moList = merchantOptions.value;
    let size = moList.length;
    let selObj = null;
    for(let i = 0 ; i < size;i++){
        if(moList[i].id == val){
          selObj = moList[i];
          break;
        }
    }

    showProDetail.value = true;
    projectDetails.value = selObj;


}

//选择任务
const selectTask = (val:any)=>{
    let pvList = projectOptions.value;
    let size = pvList.length;
    for(let i = 0 ; i < size ; i++){
        if(pvList[i].id == val){
          selTask.value = pvList[i];
          break;
        }
    }

}


const props = defineProps({
    modelValue: {
        type: Boolean
    },
    businessTypeOptions: {},
})
</script>

<style scoped lang="scss">

  :deep(.el-descriptions__body .el-descriptions__table:not(.is-bordered) .el-descriptions__cell) {
       padding-bottom: 2px;
  }

.product-detail {
  padding: 15px;
  border: 1px solid #ddd;
  width: 100%;
  max-height: 280px;
  overflow: auto;
  background-color: rgb(249, 249, 249);
  border-radius: 5px;
  :deep(.el-descriptions__body) {
    background-color: rgb(249, 249, 249);
  }

  :deep(.product-detail__title){
    border-bottom:  1px solid #ddd;
    width: 600px;
    display: flex;
    align-items: center;
    img {
      display: block;
      margin-right: 15px;
    }
  }
}
</style>
